package com.vision.shop.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.vision.shop.dao.IAddressDao;
import com.vision.shop.dao.IUserDao;
import com.vision.shop.model.Address;
import com.vision.shop.model.ShopDi;
import com.vision.shop.model.User;
import com.vision.shop.util.RequestUtil;

public class AddressServlet extends BaseServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private IUserDao userDao;
	private IAddressDao addressDao;
	@ShopDi
	public void setAddressDao(IAddressDao addressDao) {
		this.addressDao = addressDao;
	}

	@ShopDi
	public void setUserDao(IUserDao userDao) {
		this.userDao = userDao;
	}

	@Auth
	public String add(HttpServletRequest req,HttpServletResponse resp){
		Address a=(Address)RequestUtil.setParam(Address.class, req);
		User u=userDao.load(Integer.parseInt(req.getParameter("userId")));
		if(!RequestUtil.validate(Address.class, req)){
			//出错还要把用户设进去要不然没有值
			req.setAttribute("user", u);
			return "address/addInput.jsp";
		}
		addressDao.add(a, u.getId());
		return "redirect:/user.do?method=show&id="+u.getId();
	}
	@Auth
	public String addInput(HttpServletRequest req,HttpServletResponse resp){
		User u=userDao.load(Integer.parseInt(req.getParameter("userId")));
		req.setAttribute("user", u);
		return "address/addInput.jsp";
	}
	@Auth
	public String delete(HttpServletRequest req,HttpServletResponse resp){
		int addressId=Integer.parseInt(req.getParameter("id"));
		int userId=Integer.parseInt(req.getParameter("userId"));
		addressDao.delete(addressId);
		return "redirect:/user.do?method=show&id="+userId;
	}
	@Auth
	public String updateInput(HttpServletRequest req,HttpServletResponse resp){
		Address address=addressDao.load(Integer.parseInt(req.getParameter("id")));
		req.setAttribute("address", address);
		return "address/updateInput.jsp";
	}
	@Auth
	public String update(HttpServletRequest req,HttpServletResponse resp){
		Address address=addressDao.load(Integer.parseInt(req.getParameter("id")));
		Address ta=(Address)RequestUtil.setParam(Address.class, req);
		address.setName(ta.getName());
		address.setPhone(ta.getPhone());
		address.setPostcode(ta.getPostcode());
		if(!RequestUtil.validate(Address.class, req)){
			//验证不成功还要存进去
			req.setAttribute("address", address);
			return "address/updateInput.jsp";
		}
		addressDao.update(address);
		return "redirect:/user.do?method=show&id="+address.getUser().getId();
	}
}
